// pages/buy/buy.js
import { getUserInfo } from '../../utils/storage'
import { personInfo, getWechatProOpenIdIdByCode, bpPay } from '../../api/index'
import { showLoading, showToast, hideLoading } from '../../utils/toast'
import { trackingEventMap, trackingEvent } from '../../utils/tracking'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popupShow: false,
    userName: '',
    personInfo: {
      inviterRecord: [],
      packageList: []
    },
    packageData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPersonInfo()
    if (getUserInfo()) {
      let userInfo = JSON.parse(getUserInfo())
      this.setData({
        userName: userInfo.userName
      })
    }
    trackingEvent(trackingEventMap.buyPageView)
  },
  // 会员信息
  async getPersonInfo() {
    let result = await personInfo({
      queryType: 2
    })
    if (result.packageList && result.packageList.length) {
      result.packageList = result.packageList.sort((a, b) => {
        return b.discountAmt - a.discountAmt
      })
    }
    this.setData({
      personInfo: result || {
        inviterRecord: [],
        packageList: []
      }
    })
  },
  popupModel() {
    this.setData({ popupShow: true });
  },
  onClose() {
    this.setData({ popupShow: false });
  },
  // 选择套餐
  selectPack(e) {
    let packageData = e.currentTarget.dataset.package
    this.setData({
      packageData
    })
  },
  // 支付
  payData() {
    let { packageCode } = this.data.packageData
    if (!packageCode) {
      showToast('请选择充值套餐')
      return
    }
    wx.login({
      success: async (res) => {
        let code = res.code
        try {
          showLoading('获取数据中')
          let result = await getWechatProOpenIdIdByCode({ code })
          let payResult = await bpPay({
            channelNo: 'wechat-pro',
            openId: result.openid,
            packageCode
          })
          hideLoading()
          wx.requestPayment({
            timeStamp: payResult.timeStamp.toString(),
            nonceStr: payResult.nonceStr,
            package: payResult.packageStr,
            signType: payResult.signType,
            paySign: payResult.paySign,
            success(res) {
              showToast('充值成功')
              wx.redirectTo({
                url: '/pages/chatView/chatView?source=chatBuy'
              })
            },
            fail(res) {
              console.info(res)
              console.info('支付失败')
            }
          })
        } catch (error) {
          console.info('error')
          console.info(error)
          setTimeout(() => {
            hideLoading()
          }, 2000)
        }
      },
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})